package com.example.spring.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.spring.demo.common.error.CustomException;
import com.example.spring.demo.common.local.JwtUtil;
import com.example.spring.demo.common.model.req.ForgetParam;
import com.example.spring.demo.common.model.req.UpdateParam;
import com.example.spring.demo.common.model.vo.WxLoginVo;
import com.example.spring.demo.entity.UserToken;
import com.example.spring.demo.entity.WxUser;
import com.example.spring.demo.common.model.vo.WxUserParam;
import com.example.spring.demo.service.TokenService;
import com.example.spring.demo.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/wxUser")
public class WxUserController {
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private TokenService tokenService;

    //注册
    @PostMapping("/register")
    public String register(@RequestBody WxUser wxUser){
        //判断用户是否被占用
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(WxUser::getUsername,wxUser.getUsername());
        //查询用户
        WxUser user = wxUserService.getOne(wrapper);
        if(user != null){
            throw new CustomException("用户被占用！重新填写！");
        }
        //密码加密
        String pwd = DigestUtils.md5DigestAsHex(wxUser.getPassword().getBytes());
        wxUser.setPassword(pwd);
        //保存
        if(wxUserService.saveOrUpdate(wxUser)){
            return "注册成功！";
        }
        throw new CustomException("注册失败！");
    }

    //登录
    @PostMapping("/login")
    public WxLoginVo login(@RequestBody WxUser user){
        //构造查询条件
        QueryWrapper<WxUser> query = new QueryWrapper<>();
        query.lambda().eq(WxUser::getUsername,user.getUsername()).eq(WxUser::getPassword,
                DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        WxUser wxUser = wxUserService.getOne(query);
        if(wxUser != null){
            if(wxUser.getStatus().equals("1")){
                throw new CustomException("您的账户被停用，请联系管理员!");
            }

            Map<String, Object> chaim = new HashMap<>();
            chaim.put("userId", wxUser.getUserId());
            chaim.put("username", wxUser.getUsername());

            String token = JwtUtil.genToken(chaim);
            // saveToken to DB
            tokenService.saveToken(UserToken.builder()
                    .userId(Math.toIntExact(wxUser.getUserId()))
                    .tokenKey(wxUser.getUserId() + token)
                    .token(token)
                    .build());

            //返回成功的数据
            WxLoginVo vo = new WxLoginVo();
            vo.setNickName(wxUser.getNickName());
            vo.setPhone(wxUser.getPhone());
            vo.setUserId(wxUser.getUserId());
            vo.setToken(token);

            return vo;
        }
        throw new CustomException("用户密码或密码错误!");
    }

    // 登出
    @GetMapping("/logout/{userId}")
    public String logout(@PathVariable Integer userId) {
        int delUserToken = tokenService.delUserToken(userId);
        if(delUserToken > 0) {
            return "登出成功";
        }
        throw new CustomException("登出失败");
    }
    //分页查询
    @GetMapping("/list")
    public IPage<WxUser> list(WxUserParam param){
        //条件构造器
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
        //构造查询条件
        if(StrUtil.isNotEmpty(param.getPhone())){
            wrapper.lambda().like(WxUser::getPhone, param.getPhone());
        }
        wrapper.lambda().orderByAsc(WxUser::getUserId);//升序
        //分页
        IPage<WxUser> page = new Page<>(param.getCurPage(),param.getPageSize());
        //查询数据
        return wxUserService.page(page, wrapper);
    }
    //启用、停用
    @PostMapping("/stopUser")
    public String stopUser(@RequestBody WxUser user){
        UpdateWrapper<WxUser> query = new UpdateWrapper<>();

        query.lambda().set(WxUser::getStatus,user.getStatus())
                .eq(WxUser::getUserId,user.getUserId());
        //update wx_user set status = #{status} where user_id = #{userId}
        if(wxUserService.update(query)){
            return "设置成功!";
        }
        throw new CustomException("设置失败!");
    }

    //重置密码
    @PostMapping("/updatePassword")
    public String updatePassword(@RequestBody WxUser user){
        //默认重置密码为666666
        String pas = "666666";
        UpdateWrapper<WxUser> query = new UpdateWrapper<>();
        query.lambda().set(WxUser::getPassword,DigestUtils.md5DigestAsHex(pas.getBytes()))
                .eq(WxUser::getUserId,user.getUserId());
        if(wxUserService.update(query)){
            return "重置成功!";
        }
        throw new CustomException("重置失败!");
    }

    //删除用户
    @DeleteMapping("/{userId}")
    public String delete(@PathVariable("userId") Long userId){
        if(wxUserService.removeById(userId)){
            return "删除成功!";
        }
        throw new CustomException("删除失败!");
    }

    //小程序更新密码
    @PostMapping("/wxUpdatePassword")
    public String wxUpdatePassword(@RequestBody UpdateParam param){
//判断原密码是否正确
        QueryWrapper<WxUser> query = new QueryWrapper<>();
        query.lambda().eq(WxUser::getUserId,param.getUserId())
                .eq(WxUser::getPassword,DigestUtils.md5DigestAsHex(param.getOldPassword().getBytes()));
        WxUser one = wxUserService.getOne(query);//查询用户
        if(one == null){
            throw new CustomException("原密码不正确!");
        }
        UpdateWrapper<WxUser> update = new UpdateWrapper<>();
        update.lambda().set(WxUser::getPassword,DigestUtils.md5DigestAsHex(param.getPassword().getBytes()))
                .eq(WxUser::getUserId,param.getUserId());
        if(wxUserService.update(update)){
            return "密码修改成功!";
        }
        throw new CustomException("密码修改失败！");
    }

    //小程序修改信息
    @PostMapping("/editInfo")
    public String editInfo(@RequestBody WxUser wxUser){
        if(wxUserService.updateById(wxUser)){
            return "修改成功!";
        }
        throw new CustomException("修改失败!");
    }
    //小程序查询个人信息
    @GetMapping("/getInfo")
    public WxUser getInfo(Long userId){
        WxUser wxUser = wxUserService.getWxUserById(userId);
        if(Objects.isNull(wxUser)) {
            throw new CustomException("用户信息不存在");
        }
        return wxUser;
    }

    //忘记密码
    @PostMapping("/forget")
    public String forget(@RequestBody ForgetParam param){
//查询用户是否存在
        QueryWrapper<WxUser> query = new QueryWrapper<>();
        query.lambda().eq(WxUser::getUsername,param.getUsername())
                .eq(WxUser::getPhone,param.getPhone());
        WxUser one = wxUserService.getOne(query);
        if(one == null){
            throw new CustomException("账户或电话号码不正确!");
        }
//更新条件
        UpdateWrapper<WxUser> update = new UpdateWrapper<>();
        update.lambda().set(WxUser::getPassword,DigestUtils.md5DigestAsHex(param.getPassword().getBytes()))
                .eq(WxUser::getUsername,param.getUsername())
                .eq(WxUser::getPhone,param.getPhone());
        if(wxUserService.update(update)){
            return "重置成功!";
        }
        throw new CustomException("修改失败!");
    }
}
